"use strict";

var ImgLoading = {};

// loading动画
var loadingParent = $('.loading'),
    loadingNumChange,
    doneCallback,
    doneLoaded = false,
    doneDelay = false,
    loadingSheep = $('#loading-sheep'),
    loadingNum = $('#loading-percent'),
    loading = 0,
    imgStartLoading = false;

function loadingCalc() {
    if (!imgStartLoading) {
        if (loading < 85) {
            if (loading % 10 == 0) {
                loading += 25;
            } else {
                loading += 35;
            }
            setTimeout(function () {
                loadingCalc();
            }, 400);
        } else if (loading < 90) {
            loading = 90;
        }
        loadingNum.text(loading + '%');
    }
}
function start() {
    // loading页面至少显示2s，防止屏幕一闪而过的情况;2s后检查是否load完成，完成则隐藏loading画面，未完成则什么都不做
    loadingSheep.removeClass('hide');
    // 假loading 计算
    loadingCalc();

    setTimeout(function () {
        if (doneLoaded) {
            _stopLoading();
        }
        doneDelay = true;
    }, 2000)
}

function _stopLoading() {
    loadingNum.text('100%')
    loadingParent.addClass('fadeOut');
    setTimeout(function () {
        // 移除loading，动画消耗内存
        loadingParent.remove();
    }, 500)
    // 清除百分比定时计算
    clearInterval(loadingNumChange);

    // 若传入回调函数则执行
    if (typeof(doneCallback) === 'function') {
        doneCallback();
    }
}

function done(elements, callback) {
    // callback参数传入，_stopLoading()使用
    if (typeof(callback) === 'function') {
        doneCallback = callback;
    }
    // 开始图片加载监听，设置标识位
    imgStartLoading = true;

    // 图片加载监听
    var imgLoad = imagesLoaded(elements, function () {
        doneLoaded = true;
        if (doneDelay) {
            _stopLoading();
        }
    });

    // 计算图片加载进度百分比
    var imgLoadedNum = 0,
        imgLoadedAll = imgLoad.images.length;
    imgLoad.on('progress', function (instance, image) {
        imgLoadedNum++;
    });

    loadingNumChange = setInterval(function () {
        loading = ~~(imgLoadedNum * imgLoadedNum / (imgLoadedAll * imgLoadedAll) * 10 + 90);
        loadingNum.text(loading + '%');
        // console.log(imgLoadedAll,imgLoadedNum)
    }, 50);
}

// 强制停止loading
function forceStop() {
    _stopLoading();
}

ImgLoading = {
    start: start,
    done: done,
    forceStop: forceStop
};
